import React, {Component} from 'react';
import {message, Upload} from 'antd';
import {LoadingOutlined, PlusOutlined} from '@ant-design/icons'
import {connect} from 'react-redux'
import {USER_EDIT} from "../../store/actions";
import {editUserInfo} from "../../api/users";

// 1. 组件
// 2. 路由
// 3. 逻辑
// 4. redux 选用
// webapp
// 先录一个视频
class Info extends Component {
  state = {
    loading: false,
    imgUrl: '',
  };

  uploadProps = {
    name: "avatar",
    listType: "picture-card",
    className: "avatar-uploader",
    showUploadList: false,
    action: "/upload",
    beforeUpload: () => {
      //上传之前处理的操作
      //比如 文件大小的限制
      this.setState({
        loading: true
      })
    },

    onChange: () => {
      //上传文件的时候 走的回调
    },

    onSuccess: (res) => {
      this.setState({
        imgUrl: res.data.imgUrl,
        loading: false
      });
      //修改个人信息的数据
      editUserInfo({uid: this.props.userInfo.uid, avatar: res.data.imgUrl}).then(response => {
        message.success(response.msg);
        //存储到仓库
        this.props.editUserInfo({avatar: res.data.imgUrl});
      })
    },
    onError(err) {
      console.log('onError', err);
    },
  };

  render() {
    let {userInfo} = this.props;
    let {avatar} = userInfo;
    return (
      <div>
        <Upload
          {...this.uploadProps}
        >
          {avatar ? <img src={avatar} alt="avatar" style={{width: '100%'}}/> :
            <div>
              {this.state.loading ? <LoadingOutlined/> : <PlusOutlined/>}
              <div className="ant-upload-text">Upload</div>
            </div>}
        </Upload>
      </div>
    );
  }
}

const mapStateToProps = (userInfoReducer) => {
  return {
    userInfo: userInfoReducer
  }
};

const mapDispatchToProps = (dispatch) => {
  return {
    editUserInfo(userInfo) {
      dispatch({type: USER_EDIT, userInfo})
    }
  }
};

export default connect(mapStateToProps, mapDispatchToProps)(Info);
